package tienda.zapateria.siszap.gui.control;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.rx.cr.gui.JInternalFrameUC;
import org.rx.cr.util.Utilitarios;
import static org.rx.cr.util.Utilitarios.alinearDatosColumnaTablaCentro;
import static org.rx.cr.util.Utilitarios.disableComponent;
import static org.rx.cr.util.Utilitarios.enableComponent;
import static org.rx.cr.util.Utilitarios.formateaAnchoColumnaTabla;
import static org.rx.cr.util.Utilitarios.resetComponents;
import tienda.zapateria.siszap.be.BEArticulo;
import tienda.zapateria.siszap.be.BECarrito;
import tienda.zapateria.siszap.be.BECompra;
import tienda.zapateria.siszap.be.BEDetalleCompra;
import tienda.zapateria.siszap.be.BEPersona;
import tienda.zapateria.siszap.be.BEProveedor;
import tienda.zapateria.siszap.be.BERelacionTalla;
import tienda.zapateria.siszap.bl.BLArticulo;
import tienda.zapateria.siszap.bl.BLCompra;
import tienda.zapateria.siszap.bl.BLDetalleCompra;
import tienda.zapateria.siszap.bl.BLRelacionTalla;
import tienda.zapateria.siszap.gui.JF_Principal;
import tienda.zapateria.siszap.gui.control.model.ModelArticuloAsignadoCompra;
import tienda.zapateria.siszap.util.UtilProveedor;

public class JIF_AdministrarCompra extends JInternalFrameUC {

    JF_Principal parent;
    BECompra be;
    BLCompra bl;
    ModelArticuloAsignadoCompra model;
    BEDetalleCompra bEDetalleCompra;
    BLDetalleCompra bLDetalleCompra;
    BEArticulo bEArticulo;
    BLArticulo bLArticulo;
    BERelacionTalla bERelacionTalla;
    BLRelacionTalla bLRelacionTalla;

    UtilProveedor utilProveedor;
    BEPersona personal_logueado;

    public JIF_AdministrarCompra(JF_Principal parent) {
        initComponents();
        this.parent = parent;
        bl = new BLCompra(parent.getConf());
        bLArticulo = new BLArticulo(parent.getConf());
        bLRelacionTalla = new BLRelacionTalla(parent.conf);
        model = new ModelArticuloAsignadoCompra();
        jtArticulo.setModel(model);
        personalizaVistaTabla();
        bLDetalleCompra = new BLDetalleCompra(parent.getConf());
        utilProveedor = new UtilProveedor(parent.getConf());
        jdcFecha.setDate(Calendar.getInstance().getTime());
        cargarNumero();
        _init();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtArticulo = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        txfTotal = new javax.swing.JTextField();
        jdcFecha = new com.toedter.calendar.JDateChooser();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txfNumero = new javax.swing.JTextField();
        jbQuitarArticulo = new javax.swing.JButton();
        jbAgregarArticulo = new javax.swing.JButton();
        jcbProveedor = new javax.swing.JComboBox();
        jbAgregarProveedor = new javax.swing.JButton();
        jbActualizarProveedor = new javax.swing.JButton();
        jbGuardar = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();
        jbAgregar = new javax.swing.JButton();
        jbSalir = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "COMPRA", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jtArticulo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jtArticulo.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jtArticuloPropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(jtArticulo);

        jLabel4.setText("Total :");

        jLabel9.setText("Fecha :");

        jLabel10.setText("Proveedor :");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel1.setText("Compra Nro. :");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txfNumero, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txfNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jbQuitarArticulo.setText("Quitar");
        jbQuitarArticulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbQuitarArticuloActionPerformed(evt);
            }
        });

        jbAgregarArticulo.setText("Agregar");
        jbAgregarArticulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAgregarArticuloActionPerformed(evt);
            }
        });

        jcbProveedor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jbAgregarProveedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tienda/zapateria/siszap/imagen/small_agregar.png"))); // NOI18N
        jbAgregarProveedor.setBorder(null);
        jbAgregarProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAgregarProveedorActionPerformed(evt);
            }
        });

        jbActualizarProveedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tienda/zapateria/siszap/imagen/small_refresh.png"))); // NOI18N
        jbActualizarProveedor.setBorder(null);
        jbActualizarProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbActualizarProveedorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jcbProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbAgregarProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbActualizarProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(31, 31, 31)
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jdcFecha, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbAgregarArticulo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbQuitarArticulo)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jbActualizarProveedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9)
                            .addComponent(jcbProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jdcFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jbAgregarProveedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbQuitarArticulo)
                    .addComponent(jbAgregarArticulo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9))
        );

        jbGuardar.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jbGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tienda/zapateria/siszap/imagen/Guardar_Min.png"))); // NOI18N
        jbGuardar.setText("GUARDAR");
        jbGuardar.setEnabled(false);
        jbGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbGuardar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jbGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jbCancelar.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tienda/zapateria/siszap/imagen/Cancelar_Min.png"))); // NOI18N
        jbCancelar.setText("CANCEL");
        jbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbCancelar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jbAgregar.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jbAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tienda/zapateria/siszap/imagen/Nuevo.png"))); // NOI18N
        jbAgregar.setText("NUEVO");
        jbAgregar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbAgregar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jbAgregar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jbSalir.setFont(new java.awt.Font("Tahoma", 0, 8)); // NOI18N
        jbSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tienda/zapateria/siszap/imagen/exit_min.png"))); // NOI18N
        jbSalir.setText("SALIR");
        jbSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbSalir.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jbSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(206, 206, 206)
                .addComponent(jbAgregar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbGuardar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbCancelar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbSalir)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jbAgregar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbGuardar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbAgregarProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAgregarProveedorActionPerformed
        // TODO add your handling code here:
        parent.insertarInternalFrame(parent.jIF_AdministrarProveedor);
    }//GEN-LAST:event_jbAgregarProveedorActionPerformed

    private void jbActualizarProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbActualizarProveedorActionPerformed
        // TODO add your handling code here:
        try {
            utilProveedor.cargarTipo(jcbProveedor);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error al cargar el proveedor" + e, "Administrar articulo", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jbActualizarProveedorActionPerformed

    private void jbAgregarArticuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAgregarArticuloActionPerformed
        // TODO add your handling code here:
        personalizaVistaTabla();
        parent.insertarInternalFrame(parent.jIFAsignarArticuloCompra);
        personalizaVistaTabla();
    }//GEN-LAST:event_jbAgregarArticuloActionPerformed

    private void jbQuitarArticuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbQuitarArticuloActionPerformed
        // TODO add your handling code here:
        try {
            if (jtArticulo.getSelectedRow() >= 0) {
                model.remove(jtArticulo.getSelectedRow());
            } else {
                JOptionPane.showMessageDialog(this, "Error al quitar el articulo de la lista. ", "Venta", JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "La lista está vacía. " + e, "Administrar pc/lap/ser", JOptionPane.INFORMATION_MESSAGE);
            Logger.getLogger(JIF_AdministrarCompra.class.getName()).log(Level.SEVERE, null, e);
        }
    }//GEN-LAST:event_jbQuitarArticuloActionPerformed

    private void jtArticuloPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jtArticuloPropertyChange
        suma();
        // TODO add your handling code here:
    }//GEN-LAST:event_jtArticuloPropertyChange

    private void jbSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalirActionPerformed
        dispose();
        jbCancelar.doClick();
    }//GEN-LAST:event_jbSalirActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbActualizarProveedor;
    private javax.swing.JButton jbAgregar;
    private javax.swing.JButton jbAgregarArticulo;
    private javax.swing.JButton jbAgregarProveedor;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbGuardar;
    private javax.swing.JButton jbQuitarArticulo;
    private javax.swing.JButton jbSalir;
    private javax.swing.JComboBox jcbProveedor;
    private com.toedter.calendar.JDateChooser jdcFecha;
    private javax.swing.JTable jtArticulo;
    private javax.swing.JTextField txfNumero;
    private javax.swing.JTextField txfTotal;
    // End of variables declaration//GEN-END:variables

    @Override
    public void _cargarCombos() throws Exception {
        utilProveedor.cargarTipo(jcbProveedor);
    }

    @Override
    public void _agregaValidadoresControl() {

        _addOperationEventsButtons(jbAgregar, jbGuardar, jbCancelar);
        _addRestoreDataEventsTable(jtArticulo);
        Utilitarios.addCharacterValidatorEvent(new Object[][]{ //{txfEstablecimientoSalud, ALFABETICO_CM, 160},
        ///{jcbProveedor, NUMERICO, 20},
        //        {txfNumTrabajadores, NUMERICO, 20},
        });
    }

    @Override
    public boolean _isDatosValidosBE() {
        return Utilitarios.isDatosLlenos(new Object[][]{
            //  {txfNumero, "Ingresar el nombre o la razón social del proveedor."},
            {jcbProveedor, "Elegir el  proveedor."}

        });
    }

    @Override
    public int _registrarBE() throws Exception {
        try {
            be = new BECompra();
            be.setFecha(Utilitarios.castDate_UTIL_SQL(jdcFecha.getDate()));
            be.setProveedorid(((BEProveedor) jcbProveedor.getSelectedItem()).getProveedorid());
            be.setNumero(txfNumero.getText());

            int idInicio = bl.obtenerUltimoId();
            bl.registrar(be);
            int id = bl.obtenerUltimoId();
            if (id != idInicio) {
                JOptionPane.showMessageDialog(this, "Se ha registrado la compra.", "Compra.", JOptionPane.INFORMATION_MESSAGE);

                //asignar articulo
                for (BERelacionTalla s : model.getList()) {
                    bEDetalleCompra = new BEDetalleCompra();
                    bEDetalleCompra.setCompraid(id);
                    bEDetalleCompra.setArticuloid(s.getArticuloid());
                    bEDetalleCompra.setCantidad(s.getCantidad());
                    bLDetalleCompra.registrar(bEDetalleCompra);

                    try {
                        bERelacionTalla = new BERelacionTalla();
                        bERelacionTalla = bLRelacionTalla.buscar(s.getRelaciontallaid());
                        bERelacionTalla.setStock(s.getStock() + s.getCantidad());
                        bLRelacionTalla.actualizarRegistro(bERelacionTalla);

                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(this, "No se modifico el stock. " + e, "Atención.", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
            return 1;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error en el registro: " + e, "Atención", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }
    @Override
    public int _guardarCambiosBE() throws Exception {
        return 1;
    }

    @Override
    public void _listarBEs() throws Exception {
        personalizaVistaTabla();
    }

    @Override
    public void _recuperarDatosBE() throws Exception {
    }

    @Override
    public void _deshabilitarControlesDatos() {
        disableComponent(new Object[]{
            txfNumero, txfTotal,
            jcbProveedor, jbAgregarProveedor, jbActualizarProveedor,
            jbAgregarArticulo, jbQuitarArticulo, jdcFecha, jtArticulo
        });
        model.clear();
        personalizaVistaTabla();
    }

    @Override
    public void _habilitarControlesDatos() {
        enableComponent(new Object[]{
            jcbProveedor, jbAgregarProveedor, jbActualizarProveedor,
            jbAgregarArticulo, jbQuitarArticulo, jdcFecha, jtArticulo
        });
        jdcFecha.setDate(Calendar.getInstance().getTime());
        model.clear();
        personalizaVistaTabla();
        cargarNumero();
    }

    @Override
    public void _resetControls() {
        resetComponents(new Object[]{
            txfNumero, txfTotal,
            jcbProveedor, jbAgregarProveedor, jbActualizarProveedor,
            jbAgregarArticulo, jbQuitarArticulo, jdcFecha, jtArticulo
        });
        jdcFecha.setDate(Calendar.getInstance().getTime());
        model.clear();
        personalizaVistaTabla();
        cargarNumero();
    }

    private void personalizaVistaTabla() {
        alinearDatosColumnaTablaCentro(0, jtArticulo);
        alinearDatosColumnaTablaCentro(1, jtArticulo);
        alinearDatosColumnaTablaCentro(2, jtArticulo);
        alinearDatosColumnaTablaCentro(3, jtArticulo);
        formateaAnchoColumnaTabla(0, jtArticulo, 80);
        formateaAnchoColumnaTabla(1, jtArticulo, 418);
        formateaAnchoColumnaTabla(2, jtArticulo, 100);
        formateaAnchoColumnaTabla(3, jtArticulo, 100);
    }

    void agregarArticulo(BERelacionTalla componente) {
        try {
            boolean c = false;
            for (int i = 0; i < model.getRowCount(); i++) {
                if (model.get(i).getRelaciontallaid() == componente.getRelaciontallaid()) {
                    JOptionPane.showMessageDialog(this, "El articulo ha sido seleccionado antes, por favor seleccione otro.", "Atención", JOptionPane.INFORMATION_MESSAGE);
                    c = true;
                }
            }
            if (c == false) {
                componente.setSubtotal(componente.getCantidad() * componente.getPreciocompra());
                model.add(componente);

                try {
                    List<BERelacionTalla> lista;
                    lista = new ArrayList<>();
                    for (int i = 0; i < model.getRowCount(); i++) {
                        lista.add(model.get(i));
                    }

                    model = new ModelArticuloAsignadoCompra(lista);
                    jtArticulo.setModel(model);
                    for (int i = 0; i < lista.size(); i++) {
                        model.add(lista.get(i));
                    }
                    suma();
                    personalizaVistaTabla();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "Error al cargar la lista. " + e, "Atención", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error al asignar el articulo.", "Atención", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public int RetornaId(BECarrito beec) {
        return beec.getCarritoid();
    }

    public final void cargarNumero() {
        try {
            int m = bl.obtenerUltimoId();
            if (m != 0) {
                int numero = Integer.parseInt(bl.buscar(m).getNumero()) + 1;
                txfNumero.setText(Integer.toString(numero));
            } else {
                txfNumero.setText("1");
            }
        } catch (Exception e) {
            System.out.println("error al numerar");
        }
    }

    public void suma() {
        double se = 0;
        try {
            if (jtArticulo.getRowCount() > 0) {
                for (int i = 0; i < jtArticulo.getRowCount(); i++) {
                    se = redondear(se + model.get(i).getSubtotal());
                }
                txfTotal.setText(Double.toString(redondear(se)));
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error al calcular el valor de edificación.", "Valorizacion de edificación", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public double redondear(double numero) {
        BigDecimal big = new BigDecimal(numero);
        big = big.setScale(2, RoundingMode.HALF_UP);
        return new Double(big.toString());
    }

}
